package org.epidroid.epidroid.androsoul.engine.contacts;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.epidroid.epidroid.androsoul.engine.AndroSoul;
import org.epidroid.epidroid.androsoul.engine.utils.Visitor;

public class ContactGroup implements Serializable {

	private static final long serialVersionUID = -6970069893237893924L;
	private String _name = null;
	private transient AndroSoul _androsoul = null;

	// List of contacts forming the group
	private List<NetsoulContact> list;

	@Override
	public String toString() {
		return _name;
	}

	public String getName() {
		return _name;
	}

	/**
	 * Create the inner list of contacts
	 */
	public ContactGroup(AndroSoul androsoul, String name) {
		_androsoul = androsoul;
		list = new ArrayList<NetsoulContact>();
		this._name = name;
	}

	/**
	 * @return iterator a the inner list
	 */
	public Iterator<NetsoulContact> iterator() {
		return list.iterator();
	}

	/**
	 * @param c
	 *            add a contact to the inner list of contacts
	 */
	public void add(NetsoulContact c) {
		if (list.contains(c))
			return;
		list.add(c);
	}

	public List<NetsoulContact> getList() {
		return list;
	}

	/**
	 * Add a contact in the group
	 * 
	 * @param name
	 *            name of the contact to be added
	 * @return Contact that has been added (created if does not previously
	 *         exists)
	 */
	public NetsoulContact add(String name) {
		NetsoulContact c = _androsoul.getDictionary().get(name);
		if (c != null)
			add(c);
		else {
			c = _androsoul.getDictionary().createContact(name);
			add(c);
		}
		return c;
	}

	public void clear() {
		list.clear();
	}

	public void accept(Visitor v) {
		v.visit(this);
	}

	public void sort(Comparator<NetsoulContact> c) {
		Collections.sort(list, c);
	}

	public int getNbConnected() {
		int res = 0;
		Iterator<NetsoulContact> it = list.iterator();
		while (it.hasNext()) {
			if (it.next().isConnected())
				res++;
		}
		return res;
	}

	public void setName(String name) {
		_name = name;
	}
}
